package com.ftdigital.primemovers_operators.fragment;


import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ftdigital.primemovers_operators.MainActivity;
import com.ftdigital.primemovers_operators.MyApplication;
import com.ftdigital.primemovers_operators.R;
import com.ftdigital.primemovers_operators.adpter.ExpendListviewAdapter;
import com.ftdigital.primemovers_operators.adpter.OngoingListViewAdapter;
import com.ftdigital.primemovers_operators.config.GlobalData;
import com.ftdigital.primemovers_operators.config.RequestAddr;
import com.ftdigital.primemovers_operators.model.AddOilHistory;
import com.ftdigital.primemovers_operators.model.AddOilUnfinishHistory;
import com.ftdigital.primemovers_operators.model.DataEntity;
import com.ftdigital.primemovers_operators.model.FinishlistEntityList;
import com.ftdigital.primemovers_operators.model.ListEntity;
import com.ftdigital.primemovers_operators.util.http.AjaxCallBack;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


/**
 * 招标
 */
@EFragment(R.layout.fragment_tender)
public class HistoryFragment extends BaseFragment {

    @ViewById(R.id.back_btn)
    ImageButton backBtn;

    @ViewById(R.id.toptitle_title)
    TextView topTitle;

    @ViewById(R.id.expandablelistview)
    ExpandableListView expandableListView;

    ExpendListviewAdapter expendListviewAdapter;
    OngoingListViewAdapter ongoingListViewAdapter;

    @ViewById(R.id.search_content)
    EditText searchContent;

    @ViewById(R.id.listview)
    RecyclerView listview;
    HistoryFragment historyFragment;

    private static int layoutheight = 0;
    private static int expendLayoutheight = 0;

    @AfterViews
    @Override
    void initView() {
        historyFragment = this;
        layoutheight = listview.getLayoutParams().height;
        expendLayoutheight = expandableListView.getLayoutParams().height;
        Log.i(GlobalData.TAG, "expendLayoutheight:" + expendLayoutheight);
        backBtn.setVisibility(View.GONE);
        topTitle.setText(getResources().getString(R.string.title_history));

        searchContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (v.getText().toString().toString().equals("")) {
                        Log.i(GlobalData.TAG, "loadData");
                        loadData();
                    } else {
                        Log.i(GlobalData.TAG, "loadResult");
                        loadResult();
                    }
                    return true;
                }
                return false;
            }
        });

        listview.setLayoutManager(new LinearLayoutManager(getActivity()));
        loadData();
        loadUnData();
    }


    private void loadData() {
        requestParams = "user_id=" + MyApplication.userInfo.getData().getUser_id();
        requestUrl = RequestAddr.addOilList + requestParams;
        xtHttp.get(requestUrl, new AjaxCallBack<Object>() {
            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                dealData(o);
//                loadUnData();
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
//                loadUnData();
            }
        });


    }

    private void loadUnData() {
        requestParams = "user_id=" + MyApplication.userInfo.getData().getUser_id();
        requestUrl = RequestAddr.addOilUnfinishList + requestParams;
        xtHttp.get(requestUrl, new AjaxCallBack<Object>() {
            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                dealUnData(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }


    AddOilHistory addOilHistory = new AddOilHistory();

    private void dealData(Object object) {
        if (addOilHistory.getData() != null){
            addOilHistory.getData().clear();
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(object.toString());
            if (jsonObject.getBoolean("flag")) {
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject secObject = jsonArray.getJSONObject(i);
                    DataEntity dataEntity = new DataEntity();
                    dataEntity.setTime(secObject.getString("time"));
                    addOilHistory.getData().add(dataEntity);
                    JSONArray thirdObject = secObject.getJSONArray("list");
                    for (int j = 0; j < thirdObject.length(); j++) {
                        JSONObject fourObject = thirdObject.getJSONObject(j);
                        ListEntity listEntity = new ListEntity();
                        listEntity.setCar_num(fourObject.getString("car_num"));
                        listEntity.setTime(fourObject.getString("time"));
                        listEntity.setPrice(fourObject.getInt("price"));
                        listEntity.setStatus(fourObject.getInt("status"));
                        listEntity.setCompany_name(fourObject.getString("company_name"));
                        listEntity.setIs_evaluate(fourObject.getString("is_evaluate"));
                        listEntity.setQty(fourObject.getString("qty"));
                        listEntity.setDate(fourObject.getString("date"));
                        listEntity.setType(fourObject.getString("type"));
                        listEntity.setOrder_id(fourObject.getInt("order_id"));
                        listEntity.setCar_type(fourObject.getString("car_type"));
                        addOilHistory.getData().get(i).getList().add(listEntity);
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        expendListviewAdapter = new ExpendListviewAdapter(historyFragment, addOilHistory);
        expandableListView.setAdapter(expendListviewAdapter);
        if (addOilHistory.getData().size() != 0) {
            expendListviewClick(0);
        }
    }

    AddOilUnfinishHistory addOilUnfinishHistory = new AddOilUnfinishHistory();

    private void dealUnData(Object object) {
//        try {
//            addOilUnfinishHistory = gson.fromJson(object.toString(), AddOilUnfinishHistory.class);
//        } catch (JsonSyntaxException e) {
//            baseModel = gson.fromJson(object.toString(), BaseModel.class);
//            Toast.makeText(getActivity(), baseModel.getMsg(), Toast.LENGTH_SHORT).show();
//            return;
//        }
        if (addOilUnfinishHistory.getData() != null) {
            addOilUnfinishHistory.getData().clear();
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(object.toString());
            if (jsonObject.getBoolean("flag")) {
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject secObject = jsonArray.getJSONObject(i);
                    ListEntity listEntity = new ListEntity();
                    listEntity.setCar_num(secObject.getString("car_num"));
                    listEntity.setTime(secObject.getString("time"));
                    listEntity.setPrice(secObject.getInt("price"));
                    listEntity.setStatus(secObject.getInt("status"));
                    listEntity.setCompany_name(secObject.getString("company_name"));
                    listEntity.setIs_evaluate(secObject.getString("is_evaluate"));
                    listEntity.setQty(secObject.getString("qty"));
                    listEntity.setDate(secObject.getString("date"));
                    listEntity.setType(secObject.getString("type"));
                    listEntity.setOrder_id(secObject.getInt("order_id"));
                    listEntity.setCar_type(secObject.getString("car_type"));
                    listEntity.setOrder_no(secObject.getString("order_no"));
                    addOilUnfinishHistory.getData().add(listEntity);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ongoingListViewAdapter = new OngoingListViewAdapter(historyFragment.getActivity(), addOilUnfinishHistory);
        listview.setAdapter(ongoingListViewAdapter);
        ongoingListViewAdapter.setOnItemClickListener(new OngoingListViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                MainActivity.getInstance().switchFragment(historyFragment, DealingDetailFragment_.builder()
                        .order_id(addOilUnfinishHistory.getData().get(position).getOrder_id())
                        .build());
            }
        });
        if (addOilUnfinishHistory.getData().size() != 0) {
            listview.setLayoutParams(new LinearLayout.LayoutParams(listview.getLayoutParams().width, layoutheight * ongoingListViewAdapter.getItemCount()));
        }else{
            listview.setLayoutParams(new LinearLayout.LayoutParams(listview.getLayoutParams().width, 0));
        }
    }


    private void loadResult() {
        requestParams = "user_id=" + MyApplication.userInfo.getData().getUser_id()
                + "&param=" + searchContent.getText().toString().trim();
        requestUrl = RequestAddr.gasListSearch + requestParams;
        xtHttp.get(requestUrl, new AjaxCallBack<Object>() {
            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                dealResultData(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    FinishlistEntityList finishlistEntityList;

    private void dealResultData(Object object) {
//        try {
//            finishlistEntityList = gson.fromJson(object.toString(), FinishlistEntityList.class);
//        } catch (JsonSyntaxException e) {
//            baseModel = gson.fromJson(object.toString(), BaseModel.class);
//            Toast.makeText(getActivity(), baseModel.getMsg(), Toast.LENGTH_SHORT).show();
//            return;
//        }
//        Log.i(GlobalData.TAG, "size:" + finishlistEntityList.getData().size());
//        expendListviewAdapter = new ExpendListviewAdapter(historyFragment, finishlistEntityList);
//        expandableListView.setAdapter(expendListviewAdapter);
//        if (finishlistEntityList.getData().size() != 0) {
//            expandableListView.setLayoutParams(new LinearLayout.LayoutParams(listview.getLayoutParams().width, (expendLayoutheight * 3 / 5) * ongoingListViewAdapter.getItemCount()));
//        }
//        expandableListView.expandGroup(0);
    }

    @Click({R.id.dealing_layout})
    @Override
    void Click(View view) {
        switch (view.getId()) {
            case R.id.dealing_layout:
//             MainActivity.getInstance().switchFragment(this, new DealingDetailFragment_());
                break;
        }
    }

    public void expendListviewClick(int position) {
        for (int i = 0; i < expendListviewAdapter.getGroupCount(); i++) {
            if (i != position) {
                expandableListView.collapseGroup(i);
            }
        }
        if (expandableListView.isGroupExpanded(0)) {
            expandableListView.collapseGroup(0);
        }else{
            expandableListView.expandGroup(position);
        }
        expandableListView.setLayoutParams(new LinearLayout.LayoutParams(listview.getLayoutParams().width,
                (expendLayoutheight * 2 / 5) * expendListviewAdapter.getGroupCount()
                        + (expendLayoutheight * 3 / 5) * expendListviewAdapter.getChildrenCount(position)));
    }

}
